#include <iostream>
#include <queue>
#include <map>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <unordered_set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
const int N=3e5+10;
pii a[N];
pii b[N];
int c[N];
ll pre[N];
bool cmp(pii a,pii b)
{
	return a.second<b.second;
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n,k;
		scanf("%d %d",&n,&k);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&a[i].first);
			a[i].second=i;
		}
		sort(a+1,a+n+1);
		ll ak=a[k].first;
		int cntk=0;
		for(int i=k;i>0;i--)
		{
			if(a[i].first!=ak) break;
			cntk++;
		}
		int idx=k;
		for(int i=k+1;i<=n;i++)
		{
			if(a[i].first==ak)
			{
				idx++;
			}
			else break;
		}
		
		for(int i=1;i<=idx;i++)
		{
			b[i]=a[i];
		}
		
		sort(b+1,b+idx+1,cmp);
		
//		for(int i=1;i<=4;i++)
//		{
//			cout<<b[i].first
//		}
		for(int i=1,kk=0;i<=idx;i++)
		{
			int num=b[i].first;
			if(num==ak)
			{
				kk++;
			}
			c[i]=kk;
		}
		
		for(int i=1;i<=idx;i++)
		{
			pre[i]=pre[i-1]+b[i].first;
		}
		ll ans=1e17;
		//cout<<idx<<endl<<cntk<<endl;
		int mk=c[idx]-cntk;
		for(int i=1;i<=idx;i++)
		{
			ll a1=pre[i];
			ll b1=pre[idx]-pre[i];
		    ll l=0;
		    if(c[idx]-c[i]<=mk) c[idx]=mk-c[idx]+c[i];
		    ll r=min(mk,c[i]);
		    ll r1=r;
		    while(l<r)
		    {
		    	ll mid=l+r>>1;
		    	ans=min(ans,max(a1-mid*ak,b1-(mk-mid)*ak));
//		    	int midl=mid-1;
//		    	int midr=mid+1;
//		    	if(midl>=0) ans=min(ans,max(a1-midl*ak,b1-(mk-midl)*ak));
//		    	if(midr<=r1) ans=min(ans,max(a1-midr*ak,b1-(mk-midr)*ak));

		    	if(a1-mid*ak<=b1-(mk-mid)*ak)
		    	{
		    		r=mid;
				}
				else l=mid+1;
			}
			ans=min(ans,max(a1-l*ak,b1-(mk-l)*ak));
			l=0;
			if(c[idx]-c[i]<=mk) c[idx]=mk-c[idx]+c[i];
			
			r=r1;
			while(l<r)
			{
				int mid=l+r>+1>1;
		    	ans=min(ans,max(a1-mid*ak,b1-(mk-mid)*ak));
//		    	int midl=mid-1;
//		    	int midr=mid+1;
//		    	if(midl>=0) ans=min(ans,max(a1-midl*ak,b1-(mk-midl)*ak));
//		    	if(midr<=r1) ans=min(ans,max(a1-midr*ak,b1-(mk-midr)*ak));
		    	
				if(a1-mid*ak>=b1-(mk-mid)*ak) l=mid;
				else r=mid-1;
			}
			ans=min(ans,max(a1-l*ak,b1-(mk-l)*ak));
		}
		cout<<ans<<endl;
	}

	return 0;
}

